import React from 'react';
import { Form, Input, Button, Select, Space, message, Transfer ,TreeSelect} from 'antd';
import { UserOutlined, TeamOutlined } from '@ant-design/icons';
import { permissionStore } from '../store/permissionStore';
import { Permission } from '../store/permissionTypes';


interface PermissionFormProps {
  type: 'create' | 'edit' | 'view';
  initialValues?: any;
  onCancel: () => void;
}

  const PermissionForm: React.FC<PermissionFormProps> = ({ type, initialValues, onCancel }) => {
  const [form] = Form.useForm();

  const onFinish = (values: Permission) => {
    permissionStore.savePermission(values);
    message.success(type === 'create' ? '创建成功' : '更新成功');
    onCancel();
  };

  const isViewMode = type === 'view';
  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
      initialValues={{
        ...initialValues,
      }}
      disabled={isViewMode}
    >
      <Form.Item
        label="权限名称"
        name="name"
        rules={[{ required: true, message: '请输入权限名称' }]}
      >
        <Input value={initialValues?.name}  />
      </Form.Item>

      <Form.Item
        label="权限编码"
        name="perCode"
        rules={[{ required: true, message: '请输入权限编码' }]}
      >
        <Input value={initialValues?.perCode}  />
      </Form.Item>

      <Form.Item
        label="权限类型"
        name="perType"
        rules={[{ required: true, message: '请选择权限类型' }]}
      >
        <Select>
            <Select.Option value="resource">菜单</Select.Option>
            <Select.Option value="action">操作</Select.Option>
            <Select.Option value="data">数据</Select.Option>
        </Select>
      </Form.Item>

      <Form.Item
        label="权限项"
        name={'menuId'}
        rules={[{ required: true, message: '请选择权限项' }]}
      >
        <TreeSelect
          treeData={permissionStore.menuTree}
          placeholder="请选择权限项"
          treeCheckable={false}
          showCheckedStrategy="SHOW_PARENT"
          style={{ width: '100%' }}
        />
      </Form.Item>

      <Form.Item
        label="角色分配"
        name="roles"
        hidden={type === 'create'}
        rules={[{ required: false, message: '请选择角色！' }]}
      >
        <Transfer
          dataSource={permissionStore.roleOptions}
          titles={['可选角色', '已选角色']}
          targetKeys={initialValues?.roles}
          onChange={(targetKeys) => {
            form.setFieldsValue({ roles: targetKeys });
          }}
          render={(item) => item.title}
          listStyle={{
            width: 300,
            height: 300,
          }}
        />
      </Form.Item>

      {!isViewMode && (
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {type === 'create' ? '创建' : '保存'}
              </Button>
              <Button onClick={onCancel}>取消</Button>
            </Space>
          </Form.Item>
        )}
    </Form>
  );
};

export default PermissionForm; 